package cn.jhc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.CookieManager;
import java.net.HttpCookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.jhc.bean.User;
import cn.jhc.dao.DaoType;
import cn.jhc.dao.TitleDAO;
import cn.jhc.dao.UserDao;
import cn.jhc.factory.DAOFactory;

/**
 * Servlet implementation class showAddUserFromServlet
 */
@WebServlet("/adduser.htm")
public class AddUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String loginname = request.getParameter("name"); 
		String password = request.getParameter("password1");
		String email = request.getParameter("email");
		String sex = request.getParameter("sex");
		String num = request.getParameter("age");
		int age=0;
		if (num == "") {			 
			age = 0;
		} else{
			age=Integer.parseInt(num);
		}			
		if(loginname!=null && password!=null && email!=null && sex!=null){
			UserDao userDao = (UserDao)DAOFactory.getDao(DaoType.USER);
			if(userDao.checkRegister(loginname)) {
				request.getRequestDispatcher("/WEB-INF/jsp/registerDefault.jsp")
					.forward(request, response);
			} else if(userDao.addUser(new User(loginname,password,email,age,sex)) && loginname!=null){
				request.getRequestDispatcher("/WEB-INF/jsp/goto.jsp")
				.forward(request, response);
			} else{				
				out.println("<script>window.alert('注册失败,请返回！');</script>");
			}
		}else {
			out.println("<script>window.alert('注册内容不能有空,请返回！');</script>");
		}
	}
}
